<template>
	<div>
		<el-table ref="table" class="custom-table" border fit style="width: 100%" :data="tableData" :class="'normal-talbe'" :column-height="40" row-key="id">
		<el-table-column v-for="(one) in fields" :key="one" min-width="160" :label="fieldsMap[one]" :fixed="one === 'oper' ? 'right' : null">
			<template slot-scope="{ row }">
				<template v-if="one === 'name'">{{allCommodityCodeObj[row.spareId].name}}<span v-if="allCommodityCodeObj[row.spareId].isDelete" class="is-plain">（已删除）</span></template>
				<template v-if="one === 'typeId'">{{allCommodityCodeObj[row.spareId].typeId | filterTypeName}}</template>
				<template v-if="one === 'model'">{{allCommodityCodeObj[row.spareId].model}}</template>
        <template v-if="one === 'spareNumber'">{{allCommodityCodeObj[row.spareId].spareNumber}}</template>
				<template v-if="one === 'unitId'">{{allCommodityCodeObj[row.spareId].unitId | filterUniteName}}</template>
        <template v-if="one === 'wareHouseId'">{{row.wareHouseId | filterHouseName}}</template>
				<template v-if="one === 'price'">{{allCommodityCodeObj[row.spareId].price}}</template>
				<template v-else-if="one === 'spareCount'">
					<el-input-number v-model="row.spareCount" :min="0" :controls="false" size="mini" style="width: 60%"/>
				</template>
        <template v-else-if="one === 'oper' && !disabled">
          <span @click.stop="del(row.spareId)" class="oprate delete">删除</span>
				</template>
			</template>
		</el-table-column>
	</el-table>
		<div class="top">
			<div class="middle">
				<el-popover
				ref="popover"
				popper-class="spare-popover"
				:disabled="disabled"
				@hide="$emit('blur')"
				@show="getList"
				v-model="visible"
				trigger="manual"
			>
			  <el-input placeholder="搜索备件名称" v-model="inputVal" class="el-input--radius" prefix-icon="el-icon-search" size="medium" readonly-ui="readonly" />
				<el-table :data="dataFilter" @row-click="rowClick">
        <el-table-column label="备件名称" prop="spareId">
					<template slot-scope="{ row }">
						{{allCommodityCodeObj[row.spareId] ? allCommodityCodeObj[row.spareId].name : ''}}
					</template>
				</el-table-column>
        <el-table-column label="备件编号" prop="spareNumber">
					<template slot-scope="{ row }">
						{{allCommodityCodeObj[row.spareId] ? allCommodityCodeObj[row.spareId].spareNumber : ''}}
					</template>
				</el-table-column>
				<el-table-column label="备件型号" prop="spareModel" />
        <el-table-column label="所在备件库" prop="wareHouseId">
					<template slot-scope="{ row }">
						{{row.wareHouseId | filterHouseName}}
					</template>
				</el-table-column>
				<el-table-column label="库存数量" prop="stockNum" />
      </el-table>
				<el-button type="text" slot="reference" size="small" v-clickoutside="hideOnly" :disabled="disabled" @click="visible = true">添加备件</el-button>
			</el-popover>
				<slot name='right'></slot>
			</div>
			<div class="right">
				<slot name='left'></slot>
			</div>
		</div>
	</div>
</template>

<script lang="ts">
import { Component, Mixins, Ref, Inject } from 'vue-property-decorator';
import widgetCommon from '../common/widgetCommon';
import { fieldsMap } from './config'
import { commonAction } from '@/utils/common'
import { state } from '@/afterSales/views/spare/store/spareData'
import Clickoutside from 'element-ui/src/utils/clickoutside';
import filterTypeName from '@/afterSales/views/spare/mixins/filterTypeName'
@Component({
  name: 'associateSpare',
  components: {},
  filters: {
    filterHouseName (id: string): string {
      return state.allHouseObj[id]?.name
    },
    filterUniteName (id: string): string {
      return state.allUnitObj[id]?.typeName
    }
  },
  directives: {
    Clickoutside
  }
})
export default class extends Mixins(widgetCommon, filterTypeName) {
  [x: string]: any;
  private popperElm: any
  private inputVal = '';
  @Inject({ default: {} }) public readonly recordVM!: any;
  @Ref() public formRef!: any;
  private visible = false
  private list = []
  private fieldsMap = Object.freeze(fieldsMap)

  private rowClick (data: any) {
    const row = {
      wareHouseId: data.wareHouseId,
      spareId: data.spareId,
      spareCount: 0
    }
    console.log(row)
    if (this.value) {
      this.value.push(row)
    } else {
      this.value = [row]
      // this.$set(this, 'value', [row])
    }
    this.tableChangeValue()
  }

  private get fields () {
    if (!this.isConfig) {
      return [...this.item.displayField, ...['oper']]
    } else {
      return this.item.displayField
    }
  }

  private del (id: string) {
    this.value = this.value.filter(row => {
      return row.spareId !== id
    })
    this.tableChangeValue()
  }

  private get allCommodityCodeObj () {
    console.log(state.allCommodityCodeObj)
    return state.allCommodityCodeObj
  }

  private get dataFilter () {
    const list = this.tableData.map(item => {
      return item.spareId
    })
    const arr = this.list.filter((item: any) => {
      return !list.includes(item.spareId)
    })
    if (!this.inputVal) {
      return arr || [];
    }
    return (arr || []).filter((item: any) => {
      const name = state.allCommodityCodeObj[item.spareId]?.name
      return name.includes(this.inputVal);
    });
  }

  private get tableData () {
    return this.value || [];
  }

  private getSpareName (id: any, type: number) { // 获取备件类型名字 1类型 2备件名称
    if (type === 1) {
      const spareType = state.allSpareTypeObj[id]
      return spareType && spareType.typeName
    } else if (type === 2) {
      const spare = state.allCommodityCodeObj[id]
      return spare && spare.name
    }
    return ''
  }

  public foucs () {
    this.visible = true;
  }

  private getList () {
    commonAction({ url: '/server-work/action/stock/listAll', method: 'post', data: {} }).then(res => {
      if (res.success) {
        const list = res.data?.list || []
        list.forEach(item => {
          item.spareCount = 0
        })
        this.list = list
      }
    })
  }

  public hideOnly () {
    this.visible = false;
  }

  private beforeMount () {
    this.$nextTick(() => {
      if (this.$refs.popover as any) {
        this.popperElm = (this.$refs.popover as any).$refs.popper
      }
    })
  }
}
</script>
<style lang="stylus">
.spare-popover
  width: 700px;
  max-height: 400px;
  overflow-y: auto;
</style>

<style lang="stylus" scoped>
.delete
  color $c-danger
  cursor pointer
.el-input--radius
  margin-bottom: 12px
.top {
	display flex
	justify-content space-between
	padding-bottom 8px
	line-height 34px
	.middle {
		line-height 33px
		flex 1
		display flex
		align-items center
		.middle-btn {
			margin-left 18px
		}
	}
	.right {
		flex-basis 250px
		text-align right
	}
}
</style>
